package org.lql.algo.codecrush.week002;

/**
 * @author: liangqinglong
 * @date: 2025-07-23 17:34
 * @description: 面试题 01.08. 零矩阵 <a href="https://leetcode.cn/problems/zero-matrix-lcci/description/">...</a>
 **/
public class SetZeroes {

	/**
	 * 编写一种算法，若M × N矩阵中某个元素为0，则将其所在的行与列清零。
	 * <p>
	 * 示例 1：
	 * <p>
	 * 输入：
	 * [
	 * [1,1,1],
	 * [1,0,1],
	 * [1,1,1]
	 * ]
	 * 输出：
	 * [
	 * [1,0,1],
	 * [0,0,0],
	 * [1,0,1]
	 * ]
	 * 示例 2：
	 * <p>
	 * 输入：
	 * [
	 * [0,1,2,0],
	 * [3,4,5,2],
	 * [1,3,1,5]
	 * ]
	 * 输出：
	 * [
	 * [0,0,0,0],
	 * [0,4,5,0],
	 * [0,3,1,0]
	 * ]
	 */
	public void setZeroes(int[][] matrix) {
		int m = matrix.length;
		int n = matrix[0].length;
		boolean[] row = new boolean[m];
		boolean[] col = new boolean[n];
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (matrix[i][j] == 0) {
					row[i] = true;
					col[j] = true;
				}
			}
		}
		for (int i = 0; i < m; i++) {
			for (int j = 0; j < n; j++) {
				if (row[i] || col[j]) {
					matrix[i][j] = 0;
				}
			}
		}
	}

	public static void main(String[] args) {
		int[][] matrix = {
				{1, 1, 1},
				{1, 0, 1},
				{1, 1, 1}
		};
		new SetZeroes().setZeroes(matrix);
		for (int[] ints : matrix) {
			for (int j = 0; j < matrix[0].length; j++) {
				System.out.print(ints[j] + " ");
			}
			System.out.println();
		}

		int[][] matrix2 = {
				{0, 1, 2, 0},
				{3, 4, 5, 2},
				{1, 3, 1, 5}
		};
		new SetZeroes().setZeroes(matrix2);
		for (int[] ints : matrix2) {
			for (int j = 0; j < matrix2[0].length; j++) {
				System.out.print(ints[j] + " ");
			}
			System.out.println();
		}
	}
}
